<?php
namespace CarApi\Controller;
use Think\Controller;
//use Common\RestController;
use Common\Model\UserCarModel;
use Common\Model\UserCarCodeModel;
use Common\Model\HuanxinLogic;


class RegisterController extends Controller {

	/**
	 * 发送验证码
	 * 并验证120电话是否已经存在
	 * phone,
	 */
	public function sendVarifyCode(){
		$data['phone'] = I('phone');
		$data['plate_number'] = I('plate_number');

		if(empty($data['phone']) || empty($data['plate_number'])){
			$this->ajaxReturn(['status'=>0,'error_info'=>'手机号码不能为空 or 车牌号码不能为空']);
		}

		//检查是否能注册
		$carModel = new UserCarModel;
		$carExist = $carModel->canRegister($data['phone'],$data['plate_number']);
		if($carExist !== true){
			$this->ajaxReturn(['status'=>0,'error_info'=>$carExist]);
		}

		//生成验证码并发送
		$carCodeModel = new UserCarCodeModel;
		if(!$carCodeModel->create($data)){
			$this->ajaxReturn(['status'=>0,'error_info'=>$carCodeModel->getError()]);
		}
		$code = $carCodeModel->generateCode();
		$carCodeModel->code = $code;
		//TODO::发送验证码
		$codeId = $carCodeModel->add();
		if($codeId){
			//成功，返回成功信息
			$this->ajaxReturn(['status'=>1,'data'=>['code_id'=>$codeId,'code'=>$code]]);
		}
		$this->ajaxReturn(['status'=>0,'error_info'=>$carCodeModel->getError()]);
	}

	/**
	 * 注册120用户
	 * @return [type] [description]
	 */
	public function register(){
		$code = I('code');
		$codeId = I('code_id');
		$phone = I('phone');
		//检查验证码
		$codeModel = new UserCarCodeModel;
		$verifyRes = $codeModel->varifyCode($codeId,$code,$phone);
		if($verifyRes!== true){
			//没通过
			$this->ajaxReturn(['status'=>0,'error_info'=>$verifyRes]);
		}
		//注册用户
		$carModel = new UserCarModel;
		if(!$carModel->create()){
			//数据问题
			$this->ajaxReturn(['status'=>0,'error_info'=>$carModel->getError()]);
		}

		$res = $carModel->add();
		if($res){
			//添加环信用户
			$hx = new HuanxinLogic;
			$hx->addCarUser($res);

			$this->ajaxReturn(['status'=>1]);
		}
		$this->ajaxReturn(['status'=>0,'error_info'=>$carModel->getError()]);
	}

}